package com.gee.spring.boot.starter.opengemini.core.util;

/**
 * @author gepengjun
 * @since 2024/4/24 16:21
 */
public class HexUtil {

    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    public static String encodeHexStr(byte[] data){
        final int len = data.length;
        final char[] out = new char[len << 1];//len*2
        // two characters from the hex value.
        for (int i = 0, j = 0; i < len; i++) {
            out[j++] = DIGITS_UPPER[(0xF0 & data[i]) >>> 4];// 高位
            out[j++] = DIGITS_UPPER[0x0F & data[i]];// 低位
        }
        return new String(out);
    }

    public static byte[] decodeHexStr(String hexData){
        int len = hexData.length();

        if ((len & 0x01) != 0) {
            hexData = "0" + hexData;
            len = hexData.length();
//			throw new UtilException("Odd number of characters.");
        }

        final byte[] out = new byte[len >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(hexData.charAt(j), j) << 4;
            j++;
            f = f | toDigit(hexData.charAt(j), j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    private static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit < 0) {
            String msg = String.format("Illegal hexadecimal character %s at index %s", ch, index);
            throw new RuntimeException(msg);
        }
        return digit;
    }

}
